var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;   //mongodb自带对象
var url = "mongodb://localhost:27017/";
var dbname = "mall";
router.get('/123', (req, res) => {
    res.json({
        message: 'haha'
    })
})
// 注册接口
router.get('/api/register', (req, res, next) => {
    var md5 = crypto.createHash('md5');
  //   var password = req.body.password;
    var psd = md5.update(req.query.password).digest('hex');
      // console.log(req.query);
      async function as() {
          var res1 = await MongoClient.connect(url);
          var res2 = await res1.db(dbname);
          var res3 = await res2.collection('admin');
          var res4 = await res3.find({
              username: req.query.username
          }).toArray();
          if (res4.length > 0) {
              res.json({
                  code: 0,
                  message: '用户已被注册'
              })
              res1.close();
          } else {
              var insertObj = {
                username: req.query.username,
                password: psd
              }
              var res5 = await res3.insertOne(insertObj);
              var res6 = await res2.collection('admininfomation');
              var res7 = await res6.insertOne({
                username: req.query.username,
                usertype: '管理员',
                usernickname: req.query.username
              })
              res.json({
                code: 1,
                message: '注册成功'
              })
              res1.close();
          }
      }
      as(); 
  })
// 登录接口
router.get('/api/login', (req, res, next) => {
    var md5 = crypto.createHash('md5');
  //   var password = req.body.password;
    var psd = md5.update(req.query.password).digest('hex');
      // console.log(req.query);
      async function as() {
          var res1 = await MongoClient.connect(url);
          var res2 = await res1.db(dbname);
          var res3 = await res2.collection('admin');
          var res4 = await res3.find({
              username: req.query.username,
              password: psd
          }).toArray();
          if (res4.length > 0) {
              var res5 = await res2.collection('admininfomation');
              var res6 = await res5.find({
                  username: req.query.username
              }).toArray();
              res.json({
                  code: 1,
                  message: '登录成功',
                  data: res6[0]
              })
              res1.close();
          } else {
              res.json({
                code: 0,
                message: '账号或密码不正确'
              })
              res1.close();
          }
      }
      as(); 
})
// 修改密码接口
router.get('/api/changepassword', (req, res, next) => {
    var md5 = crypto.createHash('md5');
    var psd = md5.update(req.query.password).digest('hex');
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('admin');
        var res4 = await res3.find({
            username: req.query.username
        }).toArray();
        if (res4.length > 0) {
            var selectTerm = {
                username: req.query.username
            };
            var updateContent = {
                $set: {
                    password: psd
                }
            }
            res3.update(selectTerm, updateContent);
            res.json({
                code: 1,
                message: '修改密码成功'
            })
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '未找到该用户'
            })
            res1.close();
        }
    }
    as();
})
// 修改用户信息接口
router.get('/api/changeinfomation', (req, res ,next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('admininfomation');
        var selectTerm = {
            username: req.query.username
        };
        var updateContent = {
            $set: {
                usernickname: req.query.usernickname,
                useravatar: req.query.useravatar,
                desc: req.query.desc
            }
        };
        res3.updateOne(selectTerm, updateContent);
        var res4 = await res3.find(selectTerm).toArray();
        res.json({
            code: 1,
            message: '修改信息成功',
            data: res4[0]
        })
        res1.close();
    }
    as();
})
// 获取用户信息接口
router.get('/api/getuserinfomation', (req, res, next) => {
    async function as () {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('admininfomation');
        var selectTerm = {
            username: req.query.username
        }
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            res.json({
                code: 1,
                message: '查询成功',
                data: res4[0]
            })
            res1.close();
        } else {
            res1.close();
        }
    }
    as();
})
// 获取广告列表接口
router.get('/api/getadvert', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('advert');
        var selectTerm1 = {
            using: 1
        };
        var selectTerm2 = {
            using: 0
        }
        var res4 = await res3.find(selectTerm1).toArray();
        var res5 = await res3.find(selectTerm2).toArray();
        if (res4 && res5) {
            res.json({
                code: 1,
                message: '查询广告列表成功',
                data: {
                    using: res4.reverse(),
                    used: res5.reverse()
                }
            })
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '查询广告列表失败'
            })
            res1.close();
        }
    }
    as();
})
// 删除广告接口
router.get('/api/deleteadvert', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('advert');
        var selectTerm = {
            "_id": ObjectId(req.query.id)
        };
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            var res5 = await res3.deleteOne(selectTerm);
            res.json({
                code: 1,
                message: '删除广告成功'
            })
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '删除失败，广告不存在'
            })
            res1.close();
        }
    }
    as();
})
// 修改广告内容接口
router.get('/api/changeadvert', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('advert');
        var selectTerm = {
            "_id": ObjectId(req.query.id)
        };
        var updateContent = {
            $set: {
                title: req.query.title,
                author: req.query.author,
                src: req.query.src,
                date: req.query.date
            }
        };
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            res3.updateOne(selectTerm, updateContent);
            res.json({
                code: 1,
                message: '修改信息成功'
            })
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '修改信息失败，未找到'
            })
            res1.close();
        }
        
        
    }
    as();
})
// 添加广告接口
router.get('/api/addadvert', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('advert');
        var insertObj = {
            "title" : req.query.title,
            "author" : req.query.author,
            "src" : req.query.src,
            "date" : req.query.date,
            "using" : 1
        };
        var res4 = res3.insertOne(insertObj);
        res.json({
            code: 1,
            message: '添加广告成功'
        })
        res1.close();
    }
    as();
})
// 获取所有商品接口
router.get('/api/getallgoods', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goods');
        var res4 = await res3.find({}).toArray();
        res.json({
            code: 1,
            message: '查询所有商品成功',
            data: res4
        });
        res1.close();
    }
    as();
})
// 搜索商品接口
router.get('/api/selectgood', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goods');
        var selectTerm = req.query;
        var pageNumber = selectTerm.pagenumber;
        var selectTerm1 = {};
        Object.keys(selectTerm).forEach((key) => {
            if (key !== 'pagenumber') {
                selectTerm1[key] = selectTerm[key];
            }
        })
        // res.json({
        //     code: 1,
        //     data: selectTerm1
        // })
        var res4 = await res3.find(selectTerm1).limit(10).skip((parseInt(pageNumber)-1)*10).toArray();
        var res5 = await res3.find(selectTerm1).toArray();
        if (res4.length > 0) {
            res.json({
                code: 1,
                message: '搜索成功',
                data: res4,
                total: res5.length
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '未找到商品',
                total: 0
            });
            res1.close();
        }
    }
    as();
})
// 添加商品接口
router.get('/api/addgood', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goods');
        var insertObj = req.query;
        var res4 = await res3.find({}).toArray();
        if (res4.length > 0) {
            // res4[res4.length-1]
            var id = parseInt(res4[res4.length-1]["id"]) + 1;
            insertObj = Object.assign(insertObj, {"id": String(id)});
            var res5 = await res3.insertOne(insertObj);
            res.json({
                code: 1,
                message: '添加商品成功'
            }) 
            res1.close();
        } else {
            insertObj = Object.assign(insertObj, {"id": "1"});
            var res5 = await res3.insertOne(insertObj);
            res.json({
                code: 1,
                message: '添加商品成功'
            }) 
            res1.close();
        }
    }
    as();
})
// 修改商品接口
router.get('/api/changegoodinfomation', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goods');
        var selectTerm = {
            "_id": ObjectId(req.query['pid'])
        };
        var updateContent = {
            $set: req.query
        };
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            res3.updateOne(selectTerm, updateContent);
            res.json({
                code: 1,
                message: '修改商品成功'
            })
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '没有找到商品，修改失败'
            })
            res1.close();
        }
        // var res4 = await res3.updateOne(selectTerm, updateContent)
    }
    as();
})
// 删除商品接口
router.get('/api/deletegood', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goods');
        var selectTerm = {
            "_id": ObjectId(req.query.id)
        };
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            var res5 = await res3.deleteOne(selectTerm);
            res.json({
                code: 1,
                message: '删除商品成功'
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '未找到商品，无法删除'
            });
            res1.close();
        }
    }
    as();
})
// 搜索商品评论接口
router.get('/api/getgoodcomment', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goodcomment');
        var res4 = await res2.collection('goods');
        var selectTerm = {};
        if (req.query) {
            // Object.assign(selectTerm, req.query);
            Object.keys(req.query).forEach((key) => {
                if (key !== 'pagenumber') {
                    selectTerm[key] = req.query[key];
                }
            })
        }
        var res5 = await res4.find(selectTerm).toArray();
        if (res5.length === 1) {
            var objectId = res5[0]['_id'].toString();
            var selectTerm1 = {
                "pid": objectId
            }
            var pageNumber = req.query.pagenumber;
            var res6 = await res3.find(selectTerm1).limit(10).skip(10*(parseInt(pageNumber)-1)).toArray();
            var res7 = await res3.find(selectTerm1).toArray();
            res.json({
                code: 1,
                message: '搜索商品评论成功',
                data: res6,
                total: res7.length
            });
            res1.close();            
        } else {
            res.json({
                code: 0,
                message: '未找到商品',
                data: [],
                total: 0
            });
            res1.close();
        }
    }
    as();
})
// 修改评论接口
router.get('/api/changegoodcomment', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goodcomment');
        var selectTerm = {
            "_id": ObjectId(req.query['cid'])
        };
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            var updateContent = {
                $set: req.query
            };
            var res5 = await res3.updateOne(selectTerm, updateContent)
            res.json({
                code: 1,
                message: '修改评论成功'
            })
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '修改评论失败,为找到该评论'
            })
            res1.close();
        }
        
    }
    as();
})
// 删除评论接口
router.get('/api/deletegoodcomment', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('goodcomment');
        var selectTerm = {
            '_id': ObjectId(req.query['cid'])
        };
        var res4 = await res3.find(selectTerm).toArray();
        if (res4.length > 0) {
            var res5 = await res3.deleteOne(selectTerm);
            res.json({
                code: 1,
                message: '删除评论成功'
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '没有找到评论，删除失败'
            });
            res1.close();
        }
    }
    as();
})
// 查询所有订单
router.get('/api/getorder', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('order');
        var res4 = await res3.find().toArray();
        if (res4) {
            res.json({
                code: 1,
                message: '查询所有订单成功',
                data: res4
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '查询所有订单失败'
            });
            res1.close();
        }
    }
    as();
})
// 查询订单
router.get('/api/selectorder', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('order');
        var selectTerm = {};
        if (req.query) {
            Object.keys(req.query).forEach((key) => {
                if (key !== 'pagenumber') {
                    selectTerm[key] = req.query[key]
                }
            })
        }
        var pageNumber = req.query.pagenumber;
        var res4 = await res3.find(selectTerm).limit(10).skip(10*(parseInt(pageNumber)-1)).toArray();
        var res5 = await res3.find(selectTerm).toArray();
        if (res4) {
            res.json({
                code: 1,
                message: '查询订单成功',
                data: res4,
                total: res5.length
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '查询订单失败',
                data: [],
                total: 0
            });
            res1.close();
        }
    }
    as();
})
// 修改订单内容
router.get('/api/changeorder', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('order');
        var selectTerm = {
            "_id": ObjectId(req.query['oid'])
        };
        var updateContent = {
            $set: req.query
        };
        var res4 = await res3.updateOne(selectTerm, updateContent);
        if (res4) {
            res.json({
                code: 1,
                message: '修改订单内容成功'
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '修改失败'
            });
            res1.close()
        }
    }
    as();
})
// 添加订单接口
router.get('/api/addorder', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('order');
        var res4 = await res2.collection('goods');
        var insertObj = req.query;
        var selectTerm = {
            "name": req.query.pname
        }
        
        var res4 = await res4.find(selectTerm).toArray();
        var pid = '';
        if (res4.length > 0) {
            pid = res4[0]['id']
        } else {
            res.json({
                code: 0,
                message: '商品不存在'
            });
            res1.close();
        }
        var oldOid = new ObjectId().toString();
        Object.assign(insertObj, {
            "pid": pid,
            "oid": oldOid
        });
        var res5 = await res3.insertOne(insertObj)
        if (res5) {
            var selectTerm = {"oid": oldOid};
            var res6 = await res3.find(selectTerm).toArray();
            var updateContent = {
                $set: {
                    "oid": res6[0]["_id"].toString()
                }
            }
            var res7 = await res3.updateOne(selectTerm, updateContent);
            res.json({
                code: 1,
                message: '添加订单成功'
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '添加失败'
            });
            res1.close();
        }
    }
    as();
})
// 删除订单接口
router.get('/api/deleteorder', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection('order');
        var selectTerm = {
            "_id": ObjectId(req.query.oid)
        };
        var res4 = await res3.deleteOne(selectTerm);
        if (res4) {
            res.json({
                code: 1,
                message: '删除订单成功'
            });
            res1.close()
        } else {
            res.json({
                code: 0,
                message: '删除失败'
            });
            res1.close();
        }
    }
    as();
})
// 获取所有用户信息
router.get('/api/getusers', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection("users");
        var res4 = await res3.find().toArray();
        if (res4) {
            res.json({
                code: 1,
                message: '查询所有用户成功',
                data: res4,
                total: res4.length
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '查询失败'
            });
            res1.close();
        }
    }
    as();
})
// 查询用户接口
router.get('/api/selectuser', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection("users");
        var selectTerm = {}
        if (req.query) {
            Object.keys(req.query).forEach((key) => {
                if (key !== 'pagenumber') {
                    selectTerm[key] = req.query[key]
                }
            })
        }
        var res4 = await res3.find(selectTerm).toArray();
        // var res5 = await res3.find(selectTerm).limit(10).toArray()
        if (res4) {
            res.json({
                code: 1,
                message: '查询用户成功',
                data: res4,
                total: res4.length
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '查询用户失败',
                data: [],
                total: 0
            });
            res1.close();
        }
    }
    as();
})
// 修改用户接口
router.get('/api/changeuser', (req, res, next) => {
    async function as() {
        var res1 = await MongoClient.connect(url);
        var res2 = await res1.db(dbname);
        var res3 = await res2.collection("users");
        var selectTerm = {
            "id": parseInt(req.query.id)
        };
        var updateContent = {
            $set: req.query
        };
        var res4 = await res3.updateOne(selectTerm, updateContent)
        if (res4) {
            res.json({
                code: 1,
                message: '修改用户信息成功'
            });
            res1.close();
        } else {
            res.json({
                code: 0,
                message: '修改失败'
            });
            res1.close();
        }
    }
    as();
})





module.exports = router;